package net.xuele.learn.mq;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class RocketMQProducerConfiguration {

    /**
     * The Group name.
     */
    @Value("${rocketmq.producer.groupName}")
    private String groupName;

    /**
     * The Namesrv addr.
     */
    @Value("${rocketmq.producer.namesrvAddr}")
    private String namesrvAddr;

    /**
     * The Instance name.
     */
    @Value("${rocketmq.producer.instanceName}")
    private String instanceName;

    /**
     * The Max message size.
     */
    @Value("${rocketmq.producer.maxMessageSize}")
    private int maxMessageSize ; //4M
    /**
     * The Send msg timeout.
     */
    @Value("${rocketmq.producer.sendMsgTimeout}")
    private int sendMsgTimeout ;

    @Bean(initMethod = "start",destroyMethod = "shutdown")
    public DefaultMQProducer defaultMQProducer() throws RocketMQException {
        if (StringUtils.isBlank(this.groupName)) {
            throw new RocketMQException("consumerGroup is blank");
        }
        if (StringUtils.isBlank(this.namesrvAddr)) {
            throw new RocketMQException("nameServerAddr is blank");
        }
        if (StringUtils.isBlank(this.instanceName)){
            throw new RocketMQException("instanceName is blank");
        }
        DefaultMQProducer producer;
        producer = new DefaultMQProducer(this.groupName);
        producer.setNamesrvAddr(this.namesrvAddr);
        producer.setInstanceName(instanceName);
        producer.setMaxMessageSize(this.maxMessageSize);
        producer.setSendMsgTimeout(this.sendMsgTimeout);
        producer.setRetryTimesWhenSendFailed(1);
        return producer;
    }
}
